package com.yuchen.starssdk.utils;

import android.text.TextUtils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {
    public static void clearFiles(String parentFilePath){
        File parentFile = new File(parentFilePath);
        if (parentFile.isDirectory()){
            File[] files = parentFile.listFiles();
            for (File f:files){
                if (f.isFile() && f.exists()){
                    boolean delete = f.delete();
                }
            }
        }
    }

    public static void clearFiles(String parentFilePath, final String suffix){
        File parentFile = new File(parentFilePath);
        if (parentFile.isDirectory()){
            File[] files = parentFile.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(suffix);
                }
            });
            for (File f:files){
                if (f.isFile() && f.exists()){
                    f.delete();
                }
            }
        }
    }

    public static String getStringMD5(String s){
        byte[] buffer = s.getBytes();
        MessageDigest digest = null;
        try{
            digest = MessageDigest.getInstance("MD5");
            digest.update(buffer, 0, buffer.length);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder("");
        byte[] src = digest.digest();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static Map<String, String> getFilesMD5(File dir){
        Map<String, String> map = new LinkedHashMap<>();
        if (null != dir&&dir.exists()){
            File[] files = dir.listFiles();
            Arrays.sort(files, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    long diff = f1.lastModified() - f2.lastModified();
                    if (diff > 0)
                        return -1;
                    else if (diff == 0)
                        return 1;
                    else
                        return 1;//如果 if 中修改为 返回-1 同时此处修改为返回 1  排序就会是递减
                }

                public boolean equals(Object obj) {
                    return true;
                }

            });
            for (File f:files){
                if (f.isFile()){
//                    KLog.d("xxxxx"+" "+f.getAbsolutePath() +" "+DateTimeUtil.formateDatetime(f.lastModified()));
                    String md5 = getFileMD5(f);
                    if(!TextUtils.isEmpty(md5)){
                        map.put(f.getName(),md5);
                    }
                }else{
//                    map.put(f.getName(),f.getName()+" is dir");
                }
            }
        }
        return map;
    }

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder("");
        byte[] src = digest.digest();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String readFile(String path){
        return readFile(path,1024);
    }

    public static String readFile(String path, int bufferSize){
        StringBuilder sb =  new StringBuilder();
        InputStream fis = null;
        try {
            fis = new FileInputStream(path);
            byte[] buffer = new byte[bufferSize];

            int len = 0;
            while ((len = fis.read(buffer))!=-1){
                sb.append(new String(buffer,0,len));
            }

        } catch (IOException e) {
            e.printStackTrace();
//            MyLog.JUN_KANG.d(" ***ERROR*** read file: " + e.getMessage());
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    fis = null;
                }
            }
        }
        return sb.toString();
    }

    public static List<String> readLine(String fileName) {
        List<String> list = new ArrayList<>();
        try {
            File file = new File(fileName);
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String str;

            while ((str = br.readLine())!=null) {
                list.add(str);
            }
            br.close();
            fr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024*1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    public static void copyFileUsingFileChannels(File source, File dest)
            throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }

    public static void saveFile(String content, String path) {

        FileWriter fwriter = null;
        try {
            fwriter = new FileWriter(path);
            fwriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
